package com.example.triprec.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.example.triprec.R;
import com.example.triprec.common.ScenicData;
import com.example.triprec.entity.Scenic;
import com.example.triprec.ui.activity.ScenicDetailActivity;
import com.example.triprec.ui.adapter.BannerAdapter;
import com.example.triprec.ui.adapter.ScenicAdapter;

import java.util.Collections;
import java.util.List;

public class HomeFragment extends Fragment {

    private LinearLayout llHomeIndicator;
    private ViewPager2 vpHomeBanner;
    private RecyclerView rvHomeExperiences;
    private ScenicAdapter scenicAdapter;
    private BannerAdapter bannerAdapter;

    private List<Scenic> bannerScenicList;
    private ImageView[] indicatorDots;
    private EditText etHomeSearch;

    // 轮播图自动滚动相关
    private Handler autoScrollHandler;
    private Runnable autoScrollRunnable;
    private static final int AUTO_SCROLL_DELAY = 5000; // 轮播图自动滚动间隔（毫秒）
    private boolean isAutoScrolling = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        initData();
        initListener();
        return view;
    }

    private void initView(View view) {
        vpHomeBanner = view.findViewById(R.id.vp_home_banner);
        llHomeIndicator = view.findViewById(R.id.ll_home_indicator);
        rvHomeExperiences = view.findViewById(R.id.rv_home_experiences);
        etHomeSearch = view.findViewById(R.id.et_home_search);
    }

    private void initData() {
        // 设置轮播图
        setupBanner();

        // 显示精选旅行体验（竖向滚动的景点卡片）
        showFeaturedExperiences();
    }

    private void setupBanner() {
        // 从景点列表中随机选择5个景点的图片
        bannerScenicList = getRandomScenic(5);

        // 创建并设置轮播图适配器
        bannerAdapter = new BannerAdapter(getContext(), bannerScenicList);
        vpHomeBanner.setAdapter(bannerAdapter);

        // 设置一开始显示的位置为中间，实现无限循环效果
        int startPosition = Integer.MAX_VALUE / 2;
        startPosition = startPosition - startPosition % bannerScenicList.size();
        vpHomeBanner.setCurrentItem(startPosition, false);

        // 创建指示器
        setupIndicator();

        // 注册页面切换监听，以便在页面切换时更新指示器和重置自动滚动定时器
        vpHomeBanner.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                int realPosition = position % bannerScenicList.size();
                updateIndicator(realPosition);
                stopAutoScroll();
                startAutoScroll();
            }
        });
    }

    private void setupIndicator() {
        llHomeIndicator.removeAllViews();
        indicatorDots = new ImageView[bannerScenicList.size()];

        // 创建指示器点
        for (int i = 0; i < bannerScenicList.size(); i++) {
            indicatorDots[i] = new ImageView(getContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(6, 0, 6, 0); // 设置点之间的间距
            indicatorDots[i].setLayoutParams(params);
            indicatorDots[i].setImageResource(R.drawable.bg_indicator_normal);
            llHomeIndicator.addView(indicatorDots[i]);
        }

        // 设置第一个点为选中状态
        if (indicatorDots.length > 0) {
            indicatorDots[0].setImageResource(R.drawable.bg_indicator_selected);
        }
    }

    private void updateIndicator(int position) {
        if (indicatorDots != null) {
            for (int i = 0; i < indicatorDots.length; i++) {
                indicatorDots[i].setImageResource(i == position ?
                        R.drawable.bg_indicator_selected : R.drawable.bg_indicator_normal);
            }
        }
    }

    private List<Scenic> getRandomScenic(int count) {
        List<Scenic> list = ScenicData.getScenicList();
        // 随机打乱列表
        Collections.shuffle(list);
        // 取前count张图片（如果图片总数少于count，则全部返回）
        int resultCount = Math.min(count, list.size());
        return list.subList(0, resultCount);
    }

    private void showFeaturedExperiences() {
        // 创建并设置适配器
        scenicAdapter = new ScenicAdapter(rvHomeExperiences);

        // 设置点击事件
        scenicAdapter.setOnItemClickListener(new ScenicAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Scenic scenic, int position) {
                Intent intent = new Intent(getContext(), ScenicDetailActivity.class);
                intent.putExtra("scenic_id", scenic.getId());
                startActivity(intent);
            }
        });
    }

    private void initListener() {
        // 搜索栏事件
        etHomeSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String query = s.toString().trim();
                if (query.isEmpty()) {
                    scenicAdapter.setData(ScenicData.getScenicList());
                } else {
                    List<Scenic> filteredList = ScenicData.getScenicListByName(query);
                    if (filteredList.isEmpty()) {
                        Toast.makeText(getContext(), "没有找到相关景点", Toast.LENGTH_SHORT).show();
                    }
                    scenicAdapter.setData(filteredList);
                }
            }
        });
    }

    private void startAutoScroll() {
        if (isAutoScrolling) {
            return;
        }

        isAutoScrolling = true;
        autoScrollHandler = new Handler();
        autoScrollRunnable = new Runnable() {
            @Override
            public void run() {
                int currentItem = vpHomeBanner.getCurrentItem();
                vpHomeBanner.setCurrentItem(currentItem + 1, true);
                autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY);
            }
        };

        autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY);
    }

    private void stopAutoScroll() {
        if (autoScrollHandler != null && autoScrollRunnable != null) {
            autoScrollHandler.removeCallbacks(autoScrollRunnable);
            isAutoScrolling = false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        scenicAdapter.setData(ScenicData.getScenicList());
        startAutoScroll();
    }

    @Override
    public void onPause() {
        super.onPause();
        stopAutoScroll();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopAutoScroll();
    }
} 